using System;
using System.Xml;
using System.Collections.Generic;
using System.Diagnostics;

namespace MyXmlRPCRemote
{
	public class Configuration
	{
		String _Filename;
		
		public Configuration (String Filename) {
			_Filename = Filename;
		}
		
		public Service ReadConfig() {
			try {
				Dictionary<int, Command> Commands = new Dictionary<int, Command>();
				Layout RemoteLayout = new Layout();
				List<LayoutRow> Rows = null;
				LayoutRow Row = new LayoutRow();				// dummy object
				List<LayoutElement> Elements = null;
				LayoutElement Element = new LayoutElement();	// dummy object
				
				XmlTextReader Reader = new XmlTextReader(_Filename);
				Reader.Read(); 
				Reader.MoveToContent();
				
				while (Reader.Read()) {
					
					if (Reader.IsStartElement()) {
						switch (Reader.Name) {
						case "Rows":
							Rows = new List<LayoutRow>();
							break;
						case "Row":
							Row = new LayoutRow();
							break;
						case "Elements":
							Elements = new List<LayoutElement>();
							break;
						case "Element":
							Element = new LayoutElement();
							Element.CommandID = int.Parse(Reader.GetAttribute("CommandID"));
							Element.Label = Reader.GetAttribute("Label");
							Element.Type = int.Parse(Reader.GetAttribute("Type"));
							Command Cmd = new Command();
							Cmd.CommandType = Element.Type;
							Cmd.Separator = "\n";		// default for now
							Cmd.CommandProcessInfo = new ProcessStartInfo(Reader.GetAttribute("Filename"), Reader.GetAttribute("Arguments"));
							if (Cmd.CommandType == 1) {
								Element.Height = 1;
							}
							if (Cmd.CommandType == 2) {
								Element.Height = 2;
								Cmd.ListProcessInfo = new ProcessStartInfo(Reader.GetAttribute("ListCommandFilename"), Reader.GetAttribute("ListCommandArguments"));
							}
							Elements.Add(Element);
							Commands.Add(Element.CommandID, Cmd);
							break;
						default:
							break;
						}	
					} else if (Reader.NodeType == XmlNodeType.EndElement) {
						switch (Reader.Name) {
						case "Rows":
							RemoteLayout.Rows = Rows.ToArray();
							break;
						case "Row":
							Rows.Add(Row);
							break;
						case "Elements":
							Row.Elements = Elements.ToArray();
							break;
						default:
							break;
						}	
					}
				}
				
				Service TheService = new Service();
				TheService.AddCommands(Commands);
				TheService.AddLayout(RemoteLayout);
				
				return TheService;
			} catch(Exception e) {
				throw e;
			}
				
		}
	}
}

